package threadLearn.producerconsumer.v1;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 生产者
 * 生产者-消费者实现版本一
 * @author 12609
 *
 */
public class Producer implements Runnable {

	private volatile boolean isRunning = true;
	private BlockingQueue<String> queue;
	private static AtomicInteger count = new AtomicInteger();
	private static final int SLEEPTIME = 1000;

	public Producer(BlockingQueue<String> queue) {
		this.queue = queue;
	}

	@Override
	public void run() {
		String bread = "面包" + count.incrementAndGet();
		System.out.println(Thread.currentThread().getName() + "号工人正在生产！！！");
		Random random = new Random();
		try {
			while (isRunning) {
				Thread.sleep(random.nextInt(SLEEPTIME));
				System.out.println(bread + " 加入队列。。。");
				if (!queue.offer(bread, 2, TimeUnit.SECONDS)) {
					System.out.println(bread + " 加入队列失败！！！");
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
			Thread.currentThread().interrupt();
		}
	}
	public void stop() {
		isRunning = false;
	}

}
